import React, { useState } from 'react';  
import B from './PublishModal.module.css';
import imageUrl from '../../image/share-button.png'
import Cook from './Cook';
import InputGroup from './InputGroup';

const PublishModal = () => {  
  const [publishType, setPublishType] = useState('');  
  const [subTypes, setSubTypes] = useState([]);  
  const [title, setTitle] = useState('');  
  const [steps, setSteps] = useState([{ text: '', image: '' }]);  
  const [isPublishing, setIsPublishing] = useState(false);  
  const [uploadedImages, setUploadedImages] = useState([]);//图片
  const [stepsWithImages, setStepsWithImages] = useState([{ text: '', image: '', images: [] }]);  


  // 使用一个状态变量来追踪当前选中的主类型  
  const [selectedMainType, setSelectedMainType] = useState('');  
    // 添加一个新状态变量来保存选中的子标签值  
  const [selectedSubType, setSelectedSubType] = useState('');

      // handleChangeType 函数，用于处理所有主类型选择器的变化  
      const handleChangeType = (e, type) => {  
        setSelectedMainType(type); // 更新选中的主类型  
        setSelectedSubType(''); // 重置子类型选择  
      
        // 获取并设置子类型列表  
        setSubTypes(getSubTypesByPublishType(type, e.target.value));  
      }; 

    //handleSubTypeChange函数来更新selectedSubType状态  
      const handleSubTypeChange = (e) => {  
      setSelectedSubType(e.target.value);  
  };  
  

  const handleAddStep = () => {  
    setSteps([...steps, { text: '', image: '' }]);  
    setStepsWithImages([...stepsWithImages, { text: '', image: '', images: [] }]);  
  };  

  const handleDeleteLatestStep = () => {  
    if (steps.length > 0) {  
      setSteps(steps.slice(0, -1));  
      setStepsWithImages(stepsWithImages.slice(0, -1));  
    }  
  };  
  
  const handleSubmit = async () => {  
    setIsPublishing(true);  
    // 假设有一个函数用于将数据发送到数据库  
    await sendDataToDatabase({  
      publishType,  
      title,  
      steps: steps.map(({ text, image }) => ({ text, image }))  
    });  
    setIsPublishing(false);  
  };  
  
  // 假设函数，用于获取发布类型对应的小标签  
  function getSubTypesByPublishType(type,value) {  
    // 这里应该是根据实际选择的大标签返回对应的小标签列表  
    // 以下为示例数据  
    if (type === '食用分类') {  
      return ['素食', '肉食', '汤','家常菜'];  
    } else if (type === '每日三餐') {  
      return ['早餐', '午餐','下午茶', '晚餐'];  
    }  else if (type === '主食分类') {  
      return ['炒饭', '米饭','包子', '饺子', '饼', '粥'];  
    } else if (type === '中华菜系') {  
      return ['川菜', '鲁菜','粤菜', '豫菜', '闽菜', '东北菜', '京菜', '沪菜'];  
    } else if (type === '甜点') {  
      return ['甜品', '饼干','面包', '蛋糕'];  
    } 
    // ... 其他类型的小标签  
    return [];  
  }  

    // 渲染子类型显示的部分，显示当前选中的子类型  
  const renderSubTypeDisplay = () => {  
    if (selectedSubType) {  
      return <p className={B.selected_subtype}>选择的子类型：{selectedSubType}</p>;  
    }  
    return <p className={B.selected_subtype}>请选择子类型</p>;  
  };  
  
  // 假设函数，用于发送数据到数据库  
  async function sendDataToDatabase(data) {  
    // 这里应该是将数据发送到数据库的具体实现  
    console.log('Sending data to database:', data);  
    // 模拟异步操作  
    return new Promise((resolve) => setTimeout(resolve, 1000));  
  }  
  

  //图片上传
  const handleImageUpload = (event, stepIndex) => {    
    const files = event.target.files;  
    const promises = [];  
    for (let i = 0; i < files.length; i++) {    
      const file = files[i];  
      const reader = new FileReader();  
      promises.push(new Promise((resolve, reject) => {    
        reader.onload = (e) => resolve(e.target.result);    
        reader.onerror = reject;    
        reader.readAsDataURL(file);    
      }));    
    }    
    Promise.all(promises).then((imageUrls) => {      
      const newStepsWithImages = [...stepsWithImages];      
      // 使用传入的 stepIndex 来更新对应的步骤图片列表  
      newStepsWithImages[stepIndex].images = [...newStepsWithImages[stepIndex].images, ...imageUrls];      
      setStepsWithImages(newStepsWithImages);      
    });    
  };  

  // 修改 handleImageUploadForStep 函数以传递 stepIndex 给 handleImageUpload  
  const handleImageUploadForStep = (event, stepIndex) => {    
    handleImageUpload(event, stepIndex); // 这里传递 stepIndex  
  };   
    
  //删除图片
  const handleDeleteImage = (stepIndex, imageIndex) => {    
    setStepsWithImages((prevSteps) => {    
      const newSteps = [...prevSteps];    
      newSteps[stepIndex].images.splice(imageIndex, 1);    
      return newSteps;    
    });    
  }; 
  
  return (  
    <div className={B.publish_modal}>  
      <h2 className={B.publish_title}>发布菜谱</h2>  
      <div>  
        <label className={B.select_title}>选择发布类型：</label>  
        <select  
          value={selectedMainType === '食用分类' ? selectedSubType || '' : ''}   
          onChange={(e) => handleChangeType(e, '食用分类')}   
        >  
          <option value="">食用分类</option>  
          <option value="素食">素食</option>  
          <option value="肉食">肉食</option>  
          <option value="汤">汤</option>  
          <option value="家常菜">家常菜</option>  
        </select>    
        <select value={selectedMainType === '每日三餐' ? selectedSubType || '' : ''}   
          onChange={(e) => handleChangeType(e, '每日三餐')}>  
          <option value="">每日三餐</option>  
          <option value="早餐">早餐</option>  
          <option value="午餐">午餐</option>  
          <option value="下午茶">下午茶</option> 
          <option value="晚餐">晚餐</option> 
        </select> 
        <select value={selectedMainType === '主食分类' ? selectedSubType || '' : ''}   
          onChange={(e) => handleChangeType(e, '主食分类')}>  
          <option value="">主食分类</option>  
          <option value="炒饭">炒饭</option>  
          <option value="米饭">米饭</option>  
          <option value="饺子">饺子</option> 
          <option value="包子">包子</option> 
          <option value="饼">饼</option> 
          <option value="粥">粥</option> 
        </select> 
        <select value={selectedMainType === '中华菜系' ? selectedSubType || '' : ''}   
          onChange={(e) => handleChangeType(e, '中华菜系')}>  
          <option value="">中华菜系</option>  
          <option value="川菜">川菜</option>  
          <option value="鲁菜">鲁菜</option>  
          <option value="粤菜">粤菜</option> 
          <option value="豫菜">豫菜</option> 
          <option value="闽菜">闽菜</option> 
          <option value="东北菜">东北菜</option> 
          <option value="京菜">京菜</option> 
          <option value="沪菜">沪菜</option> 
        </select> 
        <select value={selectedMainType === '甜点' ? selectedSubType || '' : ''}   
          onChange={(e) => handleChangeType(e, '甜点')}>  
          <option value="">甜点</option>  
          <option value="甜品">甜品</option>  
          <option value="饼干">饼干</option>  
          <option value="面包">面包</option> 
          <option value="蛋糕">蛋糕</option>  
        </select> 
        {subTypes.length > 0 && (  
          <div>  
            <label className={B.select_type}>选择子类型：</label>  
            <select value={selectedSubType} onChange={handleSubTypeChange}>  
              <option value="">请选择子类型</option>  
              {subTypes.map((subType) => (  
                <option key={subType} value={subType}>{subType}</option>  
              ))}  
            </select>  
            {renderSubTypeDisplay()}  
          </div>  
        )}  
      </div>  
      <div className={B.Cook}>
        <Cook />
      </div>
      <div className={B.InputGroup}> {/* 可以为这个区域添加一个类名用于样式控制 */}  
        <InputGroup />  
      </div>
      <div>  
        <h3>添加标题：</h3> 
        <div>
        <textarea className={B.text_title} placeholder='有标题，更好看' type="text" value={title} onChange={(e) => setTitle(e.target.value)} />  
        </div>
      </div>  
      {stepsWithImages.map((step, index) => (  
        <div className={B.text_content} key={index}>  
          <h3>步骤{index + 1}：</h3>  
          <textarea placeholder="输入正文..."></textarea>  
          <div className={B.image_container}> 
            <label className={B.custom_file_upload}>  
              <input type="file" accept="image/*" multiple onChange={(e) => handleImageUploadForStep(e, index)} style={{ display: 'none' }} />  
              <img className={B.upload_img} src={imageUrl} alt="上传图片" />  
            </label>  
            {step.images.map((imageUrl, imageIndex) => (  
              <div className={B.uploaded_image_wrapper} key={imageIndex} style={{ display: 'inline-block', marginRight: '15px', position: 'relative' }}>  
                <img src={imageUrl} alt="" style={{ width: '80px', height: '80px' }}/>  
                <button className={B.image_delete_btn} onClick={() => handleDeleteImage(index, imageIndex)}>x</button>  
              </div>  
            ))}    
          </div> 
        </div>  
      ))}  
      <div className={B.button_add}>  
        <button className={B.add_button} onClick={handleAddStep}>增加步骤</button>     
      </div> 
      <div className={B.button_delete}>  
        <button className={B.delete_button} onClick={handleDeleteLatestStep}>删除步骤</button> 
      </div> 
      <div className={B.button_fabu}>
        <button onClick={handleSubmit} disabled={isPublishing}>  
          {isPublishing ? '发布中...' : '发布'}  
        </button>   
      </div> 
    </div>  
  );  
};  
  
export default PublishModal;